package com.example.demo.utils;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    /**
     * 偏移小时
     *
     * @param date  日期
     * @param hours 小时
     * @return {@code Date}
     */
    public static Date offsetHour(Date date, int hours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, hours);
        return calendar.getTime();
    }


    /**
     * 获取当前时间
     *
     * @return {@code String}
     */
    public static String getDate() {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return currentDateTime.format(formatter);
    }

    /**
     * 时间转换
     *
     * @param date 日期
     * @return {@code String}
     */
    public static String convertTime(String date) {
        Instant instant = Instant.parse(date);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    /**
     * 日期转换
     *
     * @param date 日期
     * @return {@code String}
     */
    public static String convertDate(String date) {
        Instant instant = Instant.parse(date);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return localDateTime.format(formatter);
    }

    /**
     * 获取年限
     *
     * @param date 日期
     * @return {@code String}
     */
    public static String getLife(String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate birthDate = LocalDate.parse(date, formatter);
        LocalDate currentDate = LocalDate.now();
        int age = currentDate.getYear() - birthDate.getYear();
        return String.valueOf(age);
    }


}